const Router = require('koa-router')
// 引入CommodityOrders数据库模块
const CommodityOrders = require('../../models/CommodityOrders')
// 引入Users数据库模块
const Users = require('../../models/Users')
// 引入Flowers数据库模块
const Flowers = require('../../models/Flowers')
// 创建router
const CommodityOrdersRouter = new Router()
/**
 * @route POST api/commodityOrders/create
 * @description 创建订单信息接口
 * @access      接口公开
 */
CommodityOrdersRouter.post('/create',async(ctx) =>{
    const userInfo = ctx.request.body.userInfo // 用户信息
    const purchasedGoodsArr = ctx.request.body.purchasedGoodsArr //购买的商品信息
    const address = userInfo.address.filter(item => item.checked === true)[0] //商品购买的地址信息
    // 判断是否有该用户
    const user = await Users.findOne({
        _id:userInfo._id
    })
    if(!user){
        ctx.status = 403
        ctx.body = {
            status:ctx.status,
            msg:'用户不存在！',
            success:false
        }
    }else{
        if(purchasedGoodsArr.length == 0){
            ctx.status = 403
            ctx.body = {
                status:ctx.status,
                msg:'准备购买商品数量不能为0！',
                success:false
            }
        }else{
            let update = {}
            update = user
            purchasedGoodsArr.forEach(async (item) =>{
                // 正确执行时,创建集合实例化数据
                const CommodityOrder = new CommodityOrders({
                    flowerName:item.name, // 商品名称
                    type:item.type, // 商品种类
                    price:Number(item.price), // 商品价钱
                    src:item.src, // 商品图片
                    salesVolumes:item.salesVolumes, // 购买数量
                    userInfo:userInfo, // 购买者信息
                    message:ctx.request.body.message, // 用户留言
                    addressInfo:address, // 收货地址信息
                    // orderTime:ctx.request.body.orderTime, // 下单时间
                })
                // 保存到商品订单的数据库之中
                CommodityOrder.save()
                // 向用户的购买订单中添加
                update.purchasedGoods.push(CommodityOrder)
                update.totalConsumption += Number(item.price * item.salesVolumes)
                // 判断是否有该鲜花
                const flower = await Flowers.findOne({
                    _id:item._id
                })
                let updateFlower = {}
                updateFlower = flower
                item.salesVolumes && (updateFlower.inventory = updateFlower.inventory - item.salesVolumes)
                item.salesVolumes && (updateFlower.allSalesVolumes = updateFlower.allSalesVolumes + item.salesVolumes)
                await Flowers.findByIdAndUpdate(item._id, updateFlower, { new: true })
            })
            // 更新用户数据库
            await Users.findByIdAndUpdate(userInfo._id, update, { new: true })
                // 向客户端返回数据
                ctx.status = 200
                ctx.body = {
                    status:ctx.status,
                    success:true,
                    msg:'订单完成！'
                }
        }
    }   
})
/**
 * @route GET api/commodityOrders/allOrders
 * @description 获取所有的订单
 * @access      接口公开
 */
CommodityOrdersRouter.get('/allOrders',async(ctx) =>{
    // 获取所有的订单
    const data = await CommodityOrders.find({})
        // 向客户端返回数据
        ctx.status = 200
        ctx.body = {
            status:ctx.status,
            success:true,
            data,
            msg:'所有订单获取完成！'
        }
})
/**
 * @route GET api/commodityOrders/commodityOrdersQuery
 * @description 查找订单
 * @access      接口公开
 */
CommodityOrdersRouter.get('/commodityOrdersQuery',async(ctx) =>{
    // 进行模糊查询
    const flowerName =  new RegExp(ctx.query.flowerName, 'i');
    const status =  ctx.query.status == undefined ? 0 : ctx.request.query.status
    const findData = await CommodityOrders.find(
        {flowerName: flowerName ,status:status}, null,{
        limit:ctx.query.pageSize == 'undefined' ? 20 : ctx.request.query.pageSize,
        skip: ctx.query.page == 'undefined' ? 0 :(ctx.request.query.page-1) * ctx.request.query.pageSize
        }
    )
    // 向客户端返回数据
    ctx.status = 200
    ctx.body = {
        status:ctx.status,
        success:true,
        data:{
            findData
        },
        msg:'数据返回成功'
    }
})
/**
 * @route POST api/commodityOrders/updateOrderStatus
 * @description 更新订单状态
 * @access      接口公开
 */
CommodityOrdersRouter.post('/updateOrderStatus',async(ctx) =>{
    const _id = ctx.request.body._id
    const status = ctx.request.body.status
    const username = ctx.request.body.username
    // 获取订单信息
    const findOrder = await CommodityOrders.findOne({_id})
    // 获取用户信息
    const findUser = await Users.findOne({username})
    // 对用户的订单的状态进行修改
    let newPurchasedGoods = findUser.purchasedGoods.map(item => {
        if(item._id.toString() === _id){
            item.status = status
        }
        return item
    })
    if(!findOrder){
        ctx.status = 403
        ctx.body = {
            status:ctx.status,
            msg:'此订单不存在！',
            success:false
        }
    }else{
        // 对订单数据库进行更新
        const updateRolesStatus = {status}
        await CommodityOrders.findByIdAndUpdate(_id,updateRolesStatus)
        // 对用户数据库进行更新
        const updatePurchaseGoods = {purchasedGoods:newPurchasedGoods}
        await Users.findByIdAndUpdate(findUser._id,updatePurchaseGoods)
        ctx.status = 200
        ctx.body = {
            status:ctx.status,
            msg:'此订单状态更新成功！',
            success:true
        }
    }
})
/**
 * @route POST api/commodityOrders/timeCommodityOrders
 * @description 根据传来的时间返回对应的订单
 * @access      接口公开
 */
CommodityOrdersRouter.post('/timeCommodityOrders',async(ctx) =>{
    const startTime = ctx.request.body.startTime
    const endTime = ctx.request.body.endTime
    // 获取订单信息
    const findOrder = await CommodityOrders.find({orderTime: {$gte: startTime,$lt:endTime}})
        ctx.status = 200
        ctx.body = {
            status:ctx.status,
            msg:'订单信息返回成功！',
            success:true,
            data:findOrder
        }
})
/**
 * @route POST api/commodityOrders/flowerPriceRange
 * @description 根据传来的单个鲜花价钱返回对应的订单
 * @access      接口公开
 */
CommodityOrdersRouter.post('/flowerPriceRange',async(ctx) =>{
    const startPrice = ctx.request.body.startPrice
    const endPrice = ctx.request.body.endPrice
    // 获取订单信息
    const findOrders = await CommodityOrders.find({price: {$gte: startPrice,$lt:endPrice}})
        ctx.status = 200
        ctx.body = {
            status:ctx.status,
            msg:'鲜花信息返回成功！',
            success:true,
            data:findOrders
        }
})
module.exports = CommodityOrdersRouter